package org.swift.commons.xml;

import javax.xml.XMLConstants;
import java.util.*;

public class NamespaceContext implements javax.xml.namespace.NamespaceContext {
	public static final String SCHEMA_NAMESPACE = XMLConstants.W3C_XML_SCHEMA_NS_URI;
	public static final String SCHEMA_PREFIX = "xs";
	public static final String RELAX_NAMESPACE = XMLConstants.RELAXNG_NS_URI;
	public static final String RELAX_PREFIX = "ng";

	Map<String,String> nsmap = new TreeMap<String, String>();

	public NamespaceContext() {
		nsmap.put(SCHEMA_PREFIX, SCHEMA_NAMESPACE);
		nsmap.put(RELAX_PREFIX, RELAX_NAMESPACE);
	}

	public NamespaceContext setNamespaceURI(String prefix, String URI) {
		nsmap.put(prefix, URI);
		return this;
	}

	@Override
	public String getNamespaceURI(String prefix) {
		return nsmap.get(prefix);
	}

	@Override
	public String getPrefix(String namespaceURI) {
		return (String)getPrefixes(namespaceURI).next();
	}

	@Override
	public Iterator getPrefixes(String namespaceURI) {
		List<String> prefixes = new ArrayList<String>();

		for ( Map.Entry<String,String> entry : nsmap.entrySet() ) {
			if ( entry.getValue().equals(namespaceURI) ) {
				prefixes.add(entry.getKey());
			}
		}

		return prefixes.iterator();
	}
}
